package com.itwxz.system.controller.common;


import com.itwxz.common.config.QiNiuConfig;
import com.itwxz.common.core.controller.BaseController;
import com.itwxz.common.core.domain.QiNiu;
import com.itwxz.common.core.domain.R;
import com.itwxz.system.domain.po.WxzOrder;
import com.itwxz.system.service.IWxzOrderService;
import com.qiniu.common.QiniuException;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.model.FileInfo;
import com.qiniu.util.Auth;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.*;

@Slf4j
@RestController
@RequestMapping("/qiniu")
@RequiredArgsConstructor
public class QiniuController extends BaseController {
    private final QiNiuConfig qiNiuConfig;

    private final IWxzOrderService orderService;

    private static BucketManager bucketManager;

    /**
     * 自定义 qiniu 服务器上传请求
     */
    @GetMapping("/token")
    public R<QiNiu> uploadFileQiNiu() {
        Auth auth = Auth.create(qiNiuConfig.getAccessKey(), qiNiuConfig.getSecretKey());

        long expireSeconds = 600L; // 有效期 5 分钟（单位：秒）
        String upToken = auth.uploadToken(qiNiuConfig.getBucket(), null, expireSeconds, null);
        // log.info(upToken);
        return R.ok(QiNiu.builder()
                .token(upToken)
                .domain(qiNiuConfig.getDomain())
                .avatar(qiNiuConfig.getAvatar())
                .photo(qiNiuConfig.getPhoto())
                .forum(qiNiuConfig.getForum())
                .uuid(UUID.randomUUID().toString())
                .build()
        );
    }

    /**
     * 自定义 qiniu 服务器上传链接
     */
    @GetMapping("/domain")
    public R<String> getQiNiuDomain() {
        return R.ok(qiNiuConfig.getDomain());
    }

    /**
     * 自定义 qiniu 服务器删除文件
     */
    @DeleteMapping("/avatar")
    public R<String> delQiNiuAvatar() {
		String avatar = getLoginUser().getUser().getAvatar();
		// 如果头像为空，直接返回成功或者提示“头像为空，无需删除”
		if (StringUtils.isBlank(avatar))
			return R.ok("头像为空，无需删除");

		BucketManager bucketManager = getBucketManager(qiNiuConfig);

		try {
			bucketManager.delete(qiNiuConfig.getBucket(), avatar);
		} catch (QiniuException ex) {
			// 612 表示文件不存在，我们也返回删除成功
			if (ex.code() == 612) {
				log.info("文件不存在，视为删除成功: {}", avatar);
				return R.ok("删除成功（文件不存在）");
			}
			log.error(
					"删除文件失败, code={}, key={}, msg={}",
					ex.code(), avatar, ex.response.toString()
			);
			return R.fail("删除失败");
		}

		return R.ok("删除成功");
    }

    /**
     * 获取七牛云图片列表
     */
    @GetMapping("/photo-list")
    public R<Map<String, List<String>>> getOrderPhotoGrouped(@RequestParam String orderId) {
        BucketManager bucketManager = getBucketManager(qiNiuConfig);

        String prefix = qiNiuConfig.getPhoto() + "/" + orderId + "/";
        String domain = qiNiuConfig.getDomain();

        BucketManager.FileListIterator iterator = bucketManager.createFileListIterator(
                qiNiuConfig.getBucket(), prefix, 30, null);

        Map<String, List<String>> groupedPhotos = new HashMap<>();

        Auth auth = Auth.create(qiNiuConfig.getAccessKey(), qiNiuConfig.getSecretKey());
        long expireInSeconds = 3600; // 链接有效期24小时

        while (iterator.hasNext()) {
            FileInfo[] items = iterator.next();
            if (items != null) {
                for (FileInfo item : items) {
                    String key = item.key; // 例如：uploads-photo/1910/2-3.jpg
                    String encodedKey;
                    try {
                        encodedKey = URLEncoder.encode(key, java.nio.charset.StandardCharsets.UTF_8).replace("+", "%20");
                    } catch (Exception e) {
                        continue; // 编码失败则跳过
                    }
                    String publicUrl = String.format("%s/%s", domain, encodedKey);
                    String url = auth.privateDownloadUrl(publicUrl, expireInSeconds);

                    // 提取组号（假设是文件名形如：2-3.jpg）
                    String fileName = key.substring(key.lastIndexOf("/") + 1); // 2-3.jpg
                    String groupKey = fileName.split("-")[0]; // 提取 "2"

                    groupedPhotos
                            .computeIfAbsent(groupKey, k -> new ArrayList<>())
                            .add(url);
                }
            }
        }
        return R.ok(groupedPhotos);
    }

    /**
     * 删除七牛云图片
     */
    @DeleteMapping("/withdraw-photo")
    public R<String> withdrawPhoto(@RequestParam String orderId) {
        BucketManager bucketManager = getBucketManager(qiNiuConfig);

        String prefix = qiNiuConfig.getPhoto() + "/" + orderId + "/";

        try {
            // 使用游标遍历所有匹配前缀的文件（分页）
            BucketManager.FileListIterator fileListIterator = bucketManager.createFileListIterator(
                    qiNiuConfig.getBucket(), prefix, 30, null);

            while (fileListIterator.hasNext()) {
                FileInfo[] items = fileListIterator.next();
                for (FileInfo item : items) {
                    try {
                        bucketManager.delete(qiNiuConfig.getBucket(), item.key);
                        log.info("删除成功：{}", item.key);
                    } catch (QiniuException ex) {
                        log.info("删除失败：{}", item.key);
                        log.info("状态码：{}", ex.code());
                        log.info("错误信息：{}", ex.response.toString());
                    }
                }
            }
            orderService.updateById(WxzOrder.builder()
                    .id(Long.valueOf(orderId))
                    .isUploads(0)
                    .build());

            return R.ok("照片已成功撤回（删除）");

        } catch (Exception e) {
            log.error(e.getMessage());
            return R.fail("操作失败：" + e.getMessage());
        }
    }

    /**
     * 获取当前用户头像图片访问链接
     */
    @GetMapping("/avatar-url")
    public R<String> getAvatarUrl() {
        String avatarKey = getLoginUser().getUser().getAvatar();

        if (StringUtils.isBlank(avatarKey)) return R.fail("未设置头像");

        String domain = qiNiuConfig.getDomain();
        String encodedFileName;
        try {
            encodedFileName = URLEncoder.encode(avatarKey, StandardCharsets.UTF_8).replace("+", "%20");
        } catch (Exception e) {
            return R.fail("头像编码失败");
        }
        String publicUrl = String.format("%s/%s", domain, encodedFileName);

        Auth auth = Auth.create(qiNiuConfig.getAccessKey(), qiNiuConfig.getSecretKey());
        long expireInSeconds = 3600; // 链接有效期1小时
        String finalUrl = auth.privateDownloadUrl(publicUrl, expireInSeconds);

        return R.ok(finalUrl);
    }

    public static BucketManager getBucketManager(QiNiuConfig qiNiuConfig) {
        if (bucketManager == null) {
            Configuration cfg = new Configuration(Region.huanan()); // 或者 Region.autoRegion()
            Auth auth = Auth.create(qiNiuConfig.getAccessKey(), qiNiuConfig.getSecretKey());
            bucketManager = new BucketManager(auth, cfg);
        }
        return bucketManager;
    }
}
